/**
 * 蛇对象
 */
(function (window, undefined) {
    /**
     * 
     * @param {画布} map 
     * @param {蛇的属性} options  蛇节的宽高
     * body[蛇头，蛇节......] 每个蛇节的对象：颜色  位置(位置按份数来计算)
     */
    function Snake(map, options) {
        this.map = map;
        options = (options instanceof Object) ? options : {};
        this.width = options.width || 20;
        this.height = options.height || 20;
        this.body = [{ color: "red", x: 3, y: 1 }, { color: "blue", x: 2, y: 1 }, { color: "blue", x: 1, y: 1 }];//蛇身
        this.elements = [];//记录
        this.direction = "right";//默认向右运动
    }

    /**
     * 渲染蛇身
     */
    Snake.prototype.render = function () {
        for (const value of this.body) {
            const el = document.createElement("div");
            this.map.appendChild(el);
            el.style.width = this.width + "px";
            el.style.height = this.height + "px";
            el.style.backgroundColor = value.color;
            el.style.left = value.x * this.width + "px";
            el.style.top = value.y * this.height + "px";
            el.style.position = "absolute";
            this.elements.push(el);
        }
    }

    /**
     * 让蛇动起来
     */
    Snake.prototype.move = function () {
        //让第二个等于第一个 
        for (let i = this.body.length-1; i >= 1; i--) {
            this.body[i].x = this.body[i - 1].x;
            this.body[i].y = this.body[i - 1].y;
        }
        //再移动头部
        const header = this.body[0];
        switch (this.direction) {
            case "right":
                header.x++;
                break;
            case "left":
                header.x--;
                break;
            case "top":
                header.y--;
                break;
            case "bottom":
                header.y++;
                break;
            default:
                break;
        }
        //移除所有元素
        this.remove();
        //重新渲染
        this.render();
    }

    /**
     * 移除蛇身所有元素
     */
    Snake.prototype.remove = function () {
        for (let index = 0; index < this.elements.length; index++) {
            const element = this.elements[index];
            this.map.removeChild(element);
        }
        this.elements = [];
    }

    window.Snake = Snake;
})(window, undefined);

// const map = document.getElementById("map");
// const s = new Snake(map);
// s.render();
